package org.mq.mymq.nameserver.core;

import org.mq.mymq.nameserver.common.CommonCache;
import org.mq.mymq.nameserver.store.ServiceInstance;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ServiceRemoveTask
 * @Description 心跳超时服务实例移除任务
 * @Author jiarong_ye
 * @Date 2025/6/19 15:40
 * @Version 1.0
 */
public class InvalidServiceRemoveTask implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(3);
                Map<String, ServiceInstance> serviceInstanceMap = CommonCache.getServiceInstanceManager().getServiceInstanceMap();
                Map<String, ServiceInstance> validServiceInstanceMap = new HashMap<>();
                long currentTime = System.currentTimeMillis();
                Iterator<String> iterator = serviceInstanceMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String brokerReqId = iterator.next();
                    ServiceInstance serviceInstance = serviceInstanceMap.get(brokerReqId);
                    Long lastHeartBeatTime = serviceInstance.getLastHeartBeatTime();
                    if (lastHeartBeatTime != null && currentTime - serviceInstance.getLastHeartBeatTime() > 3000 * 3) {
                        iterator.remove();
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
